import {Component, OnInit} from '@angular/core';
import {BladeContainerBase} from '../../../../shared/blade/blade-container-base';
import {Company} from '../../../../entity/company.model';
import {FormBuilder, FormControl, Validators, FormsModule} from '@angular/forms';
import {CompanyService} from '../../../../service/company.service';
import {Command} from '../../../../shared/toolbar.service';
import {Subject} from 'rxjs/Rx';
import {Observable} from 'rxjs/Observable';

@Component({
  selector: 'app-company-edit',
  templateUrl: './company-edit.component.html',
  styleUrls: ['./company-edit.component.css']
})
export class CompanyEditComponent extends BladeContainerBase<Company> {
  showError: boolean = false;
  public companyItmes: Company[] = [];
  //是一个可观察的事件流中的生产者
  private searchTerms = new Subject<any>();
  private result: Observable<any>;

  constructor(
    private fb: FormBuilder,
    private companyService: CompanyService,
  ) {
    super(fb);
  }

  ngOnInit() {
    this.initCompany();
    //编辑时注册按钮和按钮命令
    if (!this.isNew) {
      //编辑
      this.commands = [
        new Command('save', '保存', 'fa fa-save', 'setofkey:update', (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
        new Command('reset', '重置', 'fa fa-save', 'setofkey:reset', (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),
      ]
    }
    else {
      let parentCompany: Company = this.parentEntity.parent;
      this.currentEntity = new Company(0, '', '', '', '', '', '', '', '', '', '', '',);
      this.currentEntity.parentId = parentCompany ? parentCompany.companyId : null;
    }
    super.ngOnInit();
  }

  /**
   * 重新构建组织结构
   *
   * @private
   * @memberof MenuEditComponent
   */
  private initCompany() {
    this.companyItmes = [];
    let companys: Company[] = this.parentEntity.companys;
    companys.forEach(company => {
      let companyItme: Company = new Company(
        company.companyId,
        company.companyName,
        company.companyCode,
        company.enName,
        company.contact,
        company.telNo,
        company.email,
        company.faxNo,
        company.city,
        company.addr,
        company.zip,
        company.introduce,
        company.parentId,
      );
      let name = '|';
      for (let i = 0; i < company.companyLevel; i++) {
        name += '— ';
      }
      companyItme.companyName = `${name}${companyItme.companyName}`;
      this.companyItmes.push(companyItme);
    });
  }

  exeSaveChange(blade: any): void {
    this.saveChange();
  }

  canSaveChange(blade: any): boolean {
    return this.hasChange() && !this.hasError() && this.showError == false;
  }

  exeReset(blade: any): void {
    if (this.showError) {
      this.showError = false;
    }
    return this.formGroup.reset(this.currentEntity);
  }

  canReset(blade: any): boolean {
    return this.hasChange();
  }

  createForm() {
    this.formGroup = this.fromBuider.group({
      'parentId': [this.currentEntity.parentId, [
        Validators.required,
      ]],
      'companyName': [this.currentEntity.companyName, [
        Validators.required,
        Validators.maxLength(50),
      ], (control: FormControl): any => this.companyNameAsnyValidator(control)],
      // (control: FormControl): any => this.companyNameAsnyValidator(control)

      'companyCode': [this.currentEntity.companyCode, [
        Validators.maxLength(20)
      ]],
      'enName': [this.currentEntity.enName, [
        Validators.maxLength(50)
      ]],

      'contact': [this.currentEntity.contact, [
        Validators.maxLength(10)
      ]],
      'telNo': [this.currentEntity.telNo, []],
      'email': [this.currentEntity.email, [
        Validators.pattern('^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$'),
        Validators.maxLength(20),
      ]],

      'faxNo': [this.currentEntity.faxNo, []],
      'city': [this.currentEntity.city, []],
      'addr': [this.currentEntity.addr, []],
      'zip': [this.currentEntity.zip, []],
      'introduce': [this.currentEntity.introduce, []],
      'companyId': [this.currentEntity.companyId, [
        Validators.required,
      ],],


    });
  }

  /**
   * 异步校验companyName是否存在
   *
   * @param {FormControl} control
   * @returns {Promise<true>}
   *
   * @memberof DicKeyEditComponent
   */
  companyNameAsnyValidator(control: FormControl): any {
    return this.companyService.hasCompanyBycompanyName(control.value, this.currentEntity.parentId, this.currentEntity.companyId)
      .map(res => res ? {exist: true} : null);
  }

  compareById(): any {
    if (this.isNew) {
      const formValue = this.formGroup.value as Company;
      this.currentEntity.parentId = formValue.parentId;
    }
  }

  /**
   * 设置表单错误对象
   *
   *
   * @memberof BladeContainerBase
   */
  setFormError(): void {
    this.formErrors = {
      'parentId': '',
      'companyName': '',
      'companyCode': '',
      'enName': '',
      'contact': '',
      'telNo': '',
      'email': '',
      'faxNo': '',
      'city': '',
      'addr': '',
      'zip': '',
      'introduce': '',
      'companyId': ''
    };
  }

  /**
   * 设置表单验证信息
   *
   *
   * @memberof BladeContainerBase
   */
  setValidationMessages(): void {
    this.validationMessages = {
      'parentId': {
        'required': '父级菜单不能为空。',
      },
      'companyName': {
        'required': '名称不能为空。',
        'maxlength': '名称不能多于50个字符长度。',
        'exist': '名称已存在',
      },
      'companyCode': {
        'maxlength': '不能多于20个字符长度。',
      },
      'enName': {
        'maxlength': '不能多于50个字符长度。',
      },
      'contact': {
        'maxlength': '不能多于10个字符长度。',
      },
      'telNo': {
        'required': '不能为空',
      },
      'email': {
        'maxlength': '电子邮箱不能多于20个字符长度。',
        'pattern': '电子邮箱由字母、数字、-、@符号组成。',
      },
      'faxNo': {},
      'city': {},
      'addr': {},
      'zip': {},
      'introduce': {},
      'companyId': {}


    };
  }

  onCreate() {
    this.create();
  }


  create(): Promise<boolean> {
    if (!this.hasError()) {
      this.bladeData.isLoading = true;
      let formValue = this.formGroup.value as Company;
      this.currentEntity.companyCode = formValue.companyCode;
      this.currentEntity.companyName = formValue.companyName;
      this.currentEntity.enName = formValue.enName;
      this.currentEntity.parentId = formValue.parentId;
      this.currentEntity.contact = formValue.contact;
      this.currentEntity.telNo = formValue.telNo;
      this.currentEntity.email = formValue.email;
      this.currentEntity.faxNo = formValue.faxNo;
      this.currentEntity.city = formValue.city;
      this.currentEntity.addr = formValue.addr;
      this.currentEntity.zip = formValue.zip;
      this.currentEntity.introduce = formValue.introduce;
      this.currentEntity.companyId = formValue.companyId;
      if (this.currentEntity.parentId == 0) {
        this.currentEntity.parentId = null;
      }

      return this.companyService.create(this.currentEntity)
        .then(res => {
          if (res) {
            let parentContainerInstance = this.parentBlade.bladeContainerInstance;
            parentContainerInstance.refresh(res);
            this.bladeService.closeBlade(this.currentBlade);
            return true;
          }
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);

    }
  }

  saveChange(): Promise<boolean> {
    if (this.canSaveChange(this.currentBlade)) {
      this.bladeData.isLoading = true;
      let formValue = this.formGroup.value as Company;
      this.currentEntity.companyCode = formValue.companyCode;
      this.currentEntity.companyName = formValue.companyName;
      this.currentEntity.enName = formValue.enName;
      this.currentEntity.parentId = formValue.parentId;
      this.currentEntity.contact = formValue.contact;
      this.currentEntity.telNo = formValue.telNo;
      this.currentEntity.email = formValue.email;
      this.currentEntity.faxNo = formValue.faxNo;
      this.currentEntity.city = formValue.city;
      this.currentEntity.addr = formValue.addr;
      this.currentEntity.zip = formValue.zip;
      this.currentEntity.introduce = formValue.introduce;
      this.currentEntity.companyId = formValue.companyId;
      if (this.currentEntity.parentId == 0) {
        this.currentEntity.parentId = null;
      }

      return this.companyService.update(this.currentEntity)
        .then(res => {
          if (res) {
            let parentContainerInstance = this.parentBlade.bladeContainerInstance;
            parentContainerInstance.refresh(res);
            this.bladeService.closeBlade(this.currentBlade);
            return true;
          }
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);

    }
  }


}


// WEBPACK FOOTER //
// ./src/app/module/basic/company/company-edit/company-edit.component.ts
